package kubeutilsappsv1

import (
	"context"
	"go-kube-mgr/utils/kubeutils/kubeutils"
	"go-kube-mgr/utils/logs"
	appsv1 "k8s.io/api/apps/v1"
	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	typedv1 "k8s.io/client-go/kubernetes/typed/apps/v1"
)

type StatefulSet struct {
	InstanceInterface typedv1.AppsV1Interface
	Item              *appsv1.StatefulSet
}

func NewStatefulSet(kubeconfig string, item *appsv1.StatefulSet) *StatefulSet {
	instance := kubeutils.ResourceInstance{}
	instance.Init(kubeconfig)
	return &StatefulSet{
		InstanceInterface: instance.Clientset.AppsV1(),
		Item:              item,
	}
}

func (d *StatefulSet) Create(namespace string) error {
	logs.Info(map[string]interface{}{"名称": d.Item.Name, "命名空间": d.Item.Namespace}, "创建statefulset")
	_, err := d.InstanceInterface.StatefulSets(namespace).Create(context.TODO(), d.Item, v1.CreateOptions{})
	return err
}

func (d *StatefulSet) Update(namespace string) error {
	logs.Info(map[string]interface{}{"名称": d.Item.Name, "命名空间": d.Item.Namespace}, "更新statefulset")
	_, err := d.InstanceInterface.StatefulSets(namespace).Update(context.TODO(), d.Item, v1.UpdateOptions{})
	return err
}

func (d *StatefulSet) Delete(namespace string, name string, gracePeriodSeconds *int64) error {
	logs.Info(map[string]interface{}{
		"名称":   d.Item.Name,
		"命名空间": d.Item.Namespace,
	}, "删除replicaset")
	deleteOption := v1.DeleteOptions{}
	if gracePeriodSeconds != nil {
		deleteOption.GracePeriodSeconds = gracePeriodSeconds
	}
	err := d.InstanceInterface.StatefulSets(namespace).Delete(context.TODO(), name, deleteOption)
	return err
}

func (d *StatefulSet) DeleteList(namespace string, namelist []string, gracePeriodSeconds *int64) error {
	//
	for _, name := range namelist {
		d.Delete(namespace, name, gracePeriodSeconds)
	}
	return nil
}

func (d *StatefulSet) List(namespace string, labelSelector string, fieldSelector string) (interface{}, error) {
	logs.Info(map[string]interface{}{"命名空间": namespace}, "查询statefulset列表")
	listOptions := v1.ListOptions{
		FieldSelector: fieldSelector,
		LabelSelector: labelSelector,
	}
	list, err := d.InstanceInterface.StatefulSets(namespace).List(context.TODO(), listOptions)
	return list.Items, err

}

func (d *StatefulSet) Get(namespace string, name string) (interface{}, error) {
	logs.Info(map[string]interface{}{"名称": name, "命名空间": namespace}, "查询statefulset详情")
	i, err := d.InstanceInterface.StatefulSets(namespace).Get(context.TODO(), name, v1.GetOptions{})
	i.APIVersion = "apps/v1"
	i.Kind = "StatefulSet"
	return i, err
}
